<?php
require_once(SITE_ROOT . 'class/db/DBAlliance.class.php');
require_once(SITE_ROOT . 'class/db/DBAllianceMember.class.php');
require_once(SITE_ROOT . 'class/db/DBCountry.class.php');
require_once(SITE_ROOT . 'class/db/DBDivision.class.php');
require_once(SITE_ROOT . 'class/db/DBLeague.class.php');
require_once(SITE_ROOT . 'class/db/DBTeam.class.php');
require_once(SITE_ROOT . 'class/db/DBFlag.class.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');
require_once(SITE_ROOT . 'class/bean/Division.class.php');
require_once(SITE_ROOT . 'class/bean/League.class.php');
require_once(SITE_ROOT . 'class/bean/Team.class.php');
require_once(SITE_ROOT . 'class/logic/HoCRanks.class.php');
require_once(SITE_ROOT . 'class/logic/HoCTableRow.class.php');
require_once(SITE_ROOT . 'class/logic/LogicCoolness.class.php');
require_once(SITE_ROOT . 'class/logic/LogicTeam.class.php');
require_once(SITE_ROOT . 'lib/PHT.php');
require_once(SITE_ROOT . 'config/constants.conf.php');

class LogicHoC {

	private static $instance;
	
	// private constructor
	private function __construct() {}

	// the getInstance() method returns a single instance of the object
	public static function getInstance() {
		if(!isset(self::$instance)) {
			self::$instance = new self;
		}
		return self::$instance;
	}
	
	public function createHoCTable($term, $type, $countryID, $divisionID, $leagueID, $allianceID, $month, $year, $startindex, $endindex, $countrysort) {
		$dbteam = new DBTeam();
		$table = array();
						
		$teams = $this->getRanking($term, $type, $countryID, $divisionID, $leagueID, $allianceID, $month, $year, $startindex, $endindex, $countrysort);
		if (count($teams) > 0) {
			$diffrank = 1;
			foreach ($teams as $index => &$team) {
				if ($index == 0) {
					$rank = $this->getHoCRank($team, $term, $type, $countryID, $divisionID, $leagueID, $allianceID, $month, $year);
					$diffrank = $startindex+1 - $rank + $diffrank;
				}
				else {
					$prevrow = $table[$index];
					if ($term == CONST_COOL) $prevrowscore = $prevrow->getCoolness();
					else if ($term == CONST_FLAG) $prevrowscore = $prevrow->getFlags();
					if ($prevrowscore == $this->getScore($team, $term, $type)) {
						$rank = $prevrow->getRank();
						$diffrank++;
					}
					else {
						$rank = $rank + $diffrank;
						$diffrank = 1;
					}
				}
				$row = new HoCTableRow($rank, $team, $term, $type);
				$table[$index+1] = $row;
			}
		}
		return $table;
	}
	
	public function getCountries() {
		$dbcountry = new DBCountry();
		$countries = $dbcountry->getCountries("name");
		return $countries;
	}
	
	public function getDivisions($countryID = null) {
		if ($countryID === null || $countryID == 0) {
			$dbdivision = new DBDivision();
			$divisions = $dbdivision->getDivisions();
		}
		else {
			$country = new Country();
			$country->setCountryID($countryID);
			$dbdivision = new DBDivision();
			$divisions = $dbdivision->getDivisionsByCountry($country, false);
		}
		return $divisions;
	}
	
	public function getLeagues($countryID, $divisionID) {
		$country = new Country();
		$country->setCountryID($countryID);
		$division = new Division();
		$division->setDivisionID($divisionID);
		$division->setCountry($country);
		$dbleague = new DBLeague();
		$leagues = $dbleague->getLeaguesByDivision($division);
		return $leagues;
	}
	
	public function getLeague($leagueID) {
		$dbleague = new DBLeague();
		$league = $dbleague->getLeague($leagueID);
		return $league;
	}
	
	public function getAlliances() {
		$dballiance = new DBAlliance();
		$alliances = $dballiance->getAlliances();
		return $alliances;
	}
    	
	public function getMonths() {
		$months = array();
		$months[0] = "Any";	
		for ($i=1; $i<13; $i++) {
			$months[$i] = date("F", mktime(0, 0, 0, $i, 1, 2000));
		}
		return $months;
	}
	
	public function getYears($month = null) {
		$years = array();
		if ($month === null || $month == 0) {
			$years[0] = "Any";
		}
		for ($i=date("Y", time()); $i>=1997; $i--) {
			$years[$i] = $i;
		}
		return $years;
	}
	
	public function getRankingCount($countryID, $divisionID, $leagueID, $allianceID, $month, $year) {
		if ($month != 0 || $year != 0) {
			if ($month == 0) {
				$frommonth = 1;
				$tomonth = 1;
				$fromyear = $year;
				$toyear = $year + 1;
			}
			else if ($month != 0) {
				$frommonth = $month;
				$tomonth = $month + 1;
				$fromyear = $year;
				$toyear = $year;
			}			
			$fromdate = mktime(0, 0, 0, $frommonth, 1, $fromyear);
			$todate = mktime(0, 0, 0, $tomonth, 1, $toyear);
		}
		
		$dbteam = new DBTeam();
		return $dbteam->getCountForHoC($countryID, $divisionID, $leagueID, $allianceID, $fromdate, $todate);
	}
	
	private function getRanking($term, $type, $countryID, $divisionID, $leagueID, $allianceID, $month, $year, $startindex, $endindex, $countrysort) {
		$orderby = $this->getOrderBy($term, $type);
		
		if ($month != 0 || $year != 0) {
			if ($month == 0) {
				$frommonth = 1;
				$tomonth = 1;
				$fromyear = $year;
				$toyear = $year + 1;
			}
			else if ($month != 0) {
				$frommonth = $month;
				$tomonth = $month + 1;
				$fromyear = $year;
				$toyear = $year;
			}			
			$fromdate = mktime(0, 0, 0, $frommonth, 1, $fromyear);
			$todate = mktime(0, 0, 0, $tomonth, 1, $toyear);
		}
		
		$dbteam = new DBTeam();
		return $dbteam->getTeamsForHoC($orderby, $countryID, $divisionID, $leagueID, $allianceID, $fromdate, $todate, $startindex, $endindex, $countrysort);
	}
	
	public function getHoCRank($team, $term, $type, $countryID = null, $divisionID = null, $leagueID = null, $allianceID = null, $month = null, $year = null) {
		$dbteam = new DBTeam();
		
		$score = $this->getScore($team, $term, $type);
		
		if ($month != 0 || $year != 0) {
			if ($month == 0) {
				$frommonth = 1;
				$tomonth = 1;
				$fromyear = $year;
				$toyear = $year + 1;
			}
			else if ($month != 0) {
				$frommonth = $month;
				$tomonth = $month + 1;
				$fromyear = $year;
				$toyear = $year;
			}			
			$fromdate = mktime(0, 0, 0, $frommonth, 1, $fromyear);
			$todate = mktime(0, 0, 0, $tomonth, 1, $toyear);
		}
		
		return $dbteam->getHoCRank($score, $term, $this->getOrderBy($term, $type), $countryID, $divisionID, $leagueID, $allianceID, $fromdate, $todate);			
	}
	
	public function getHoCRanks($teamID) {
		$dbteam = new DBTeam();
		$team = $dbteam->getTeamByID($teamID);
		
		$logic = LogicCoolness::getInstance();
		$country = $logic->getCountry($team);
		
		$positions = new HoCRanks();
		
		$positions->setTeam($team);
		$positions->setCountry($country);
		$positions->setGlobalAwayCoolness($this->getHoCRank($team, CONST_COOL, CONST_AWAY));
		$positions->setGlobalAwayFlags($this->getHoCRank($team, CONST_FLAG, CONST_AWAY));
		$positions->setGlobalHomeCoolness($this->getHoCRank($team, CONST_COOL, CONST_HOME));
		$positions->setGlobalHomeFlags($this->getHoCRank($team, CONST_FLAG, CONST_HOME));
		$positions->setGlobalAndCoolness($this->getHoCRank($team, CONST_COOL, CONST_AND));
		$positions->setGlobalAndFlags($this->getHoCRank($team, CONST_FLAG, CONST_AND));
		$positions->setGlobalOrCoolness($this->getHoCRank($team, CONST_COOL, CONST_OR));
		$positions->setGlobalOrFlags($this->getHoCRank($team, CONST_FLAG, CONST_OR));
		$positions->setGlobalPlusCoolness($this->getHoCRank($team, CONST_COOL, CONST_PLUS));
		$positions->setGlobalPlusFlags($this->getHoCRank($team, CONST_FLAG, CONST_PLUS));
		$positions->setCountryAwayCoolness($this->getHoCRank($team, CONST_COOL, CONST_AWAY, $country->getCountryID()));
		$positions->setCountryAwayFlags($this->getHoCRank($team, CONST_FLAG, CONST_AWAY, $country->getCountryID()));
		$positions->setCountryHomeCoolness($this->getHoCRank($team, CONST_COOL, CONST_HOME, $country->getCountryID()));
		$positions->setCountryHomeFlags($this->getHoCRank($team, CONST_FLAG, CONST_HOME, $country->getCountryID()));
		$positions->setCountryAndCoolness($this->getHoCRank($team, CONST_COOL, CONST_AND, $country->getCountryID()));
		$positions->setCountryAndFlags($this->getHoCRank($team, CONST_FLAG, CONST_AND, $country->getCountryID()));
		$positions->setCountryOrCoolness($this->getHoCRank($team, CONST_COOL, CONST_OR, $country->getCountryID()));
		$positions->setCountryOrFlags($this->getHoCRank($team, CONST_FLAG, CONST_OR, $country->getCountryID()));
		$positions->setCountryPlusCoolness($this->getHoCRank($team, CONST_COOL, CONST_PLUS, $country->getCountryID()));
		$positions->setCountryPlusFlags($this->getHoCRank($team, CONST_FLAG, CONST_PLUS, $country->getCountryID()));
		
		$positions->setConferenceCode($this->printConferenceCode($positions));
		
		return $positions;
	}
	
	public function printConferenceCode($positions) {
		$code = "[b]" . $positions->getTeam()->getName() . "'s ranks in Hall of Cool[/b][br]";
		$code .= "[table][tr][th rowspan=2][/th][th colspan=2 align=center]visited[/th][th colspan=2 align=center]hosted[/th][th colspan=2 align=center]visited AND hosted[/th][th colspan=2 align=center]visited OR hosted[/th][th colspan=2 align=center]visited PLUS hosted[/th][/tr]";
		$code .= "[tr][th align=center]Coolness[/th][th align=center]Flags[/th][th align=center]Coolness[/th][th align=center]Flags[/th][th align=center]Coolness[/th][th align=center]Flags[/th][th align=center]Coolness[/th][th align=center]Flags[/th][th align=center]Coolness[/th][th align=center]Flags[/th][/tr]";
		$code .= "[tr][th]Global[/th][td align=center]" . $positions->getGlobalAwayCoolness() . ".[/td][td align=center]" . $positions->getGlobalAwayFlags() . ".[/td][td align=center]" . $positions->getGlobalHomeCoolness() . ".[/td][td align=center]" . $positions->getGlobalHomeFlags() . ".[/td][td align=center]" . $positions->getGlobalAndCoolness() . ".[/td][td align=center]" . $positions->getGlobalAndFlags() . ".[/td][td align=center]" . $positions->getGlobalOrCoolness() . ".[/td][td align=center]" . $positions->getGlobalOrFlags() . ".[/td][td align=center]" . $positions->getGlobalPlusCoolness() . ".[/td][td align=center]" . $positions->getGlobalPlusFlags() . ".[/td][/tr]";
		$code .= "[tr][th]" . $positions->getCountry()->getName() . "[/th][td align=center]" . $positions->getCountryAwayCoolness() . ".[/td][td align=center]" . $positions->getCountryAwayFlags() . ".[/td][td align=center]" . $positions->getCountryHomeCoolness() . ".[/td][td align=center]" . $positions->getCountryHomeFlags() . ".[/td][td align=center]" . $positions->getCountryAndCoolness() . ".[/td][td align=center]" . $positions->getCountryAndFlags() . ".[/td][td align=center]" . $positions->getCountryOrCoolness() . ".[/td][td align=center]" . $positions->getCountryOrFlags() . ".[/td][td align=center]" . $positions->getCountryPlusCoolness() . ".[/td][td align=center]" . $positions->getCountryPlusFlags() . ".[/td][/tr][/table]";
		return $code;
	}

	public function update($teamID) {
		$logicCoolness = LogicCoolness::getInstance();
		$logicCoolness->autoUpdate($teamID, false);
	}
	
	private function getOrderBy($term, $type) {
		if ($term == CONST_FLAG) {
			switch ($type) {
				case CONST_AWAY:	return "away_flags";break;
				case CONST_HOME:	return "home_flags";break;
				case CONST_AND:		return "and_flags";break;
				case CONST_OR:		return "or_flags";break;
				case CONST_PLUS:	return "plus_flags";break;
				default:			return "away_flags";break;
			}		
		}
		else {
			switch ($type) {
				case CONST_AWAY:	return "away_coolness";break;
				case CONST_HOME:	return "home_coolness";break;
				case CONST_AND:		return "and_coolness";break;
				case CONST_OR:		return "or_coolness";break;
				case CONST_PLUS:	return "plus_coolness";break;
				default:			return "away_coolness";break;
			}
		}
	}
	
	private function getScore($team, $term, $type) {
		if ($term == CONST_COOL) {
			switch ($type) {
				case CONST_AWAY:	return $team->getAwayCoolness();
				case CONST_HOME:	return $team->getHomeCoolness();
				case CONST_AND:		return $team->getAndCoolness();
				case CONST_OR:		return $team->getOrCoolness();
				case CONST_PLUS:	return $team->getPlusCoolness();
			}			
		}
		else if ($term == CONST_FLAG) {
			switch ($type) {
				case CONST_AWAY:	return $team->getAwayFlags();
				case CONST_HOME:	return $team->getHomeFlags();
				case CONST_AND:		return $team->getAndFlags();
				case CONST_OR:		return $team->getOrFlags();
				case CONST_PLUS:	return $team->getPlusFlags();
			}
		}
	}
		
	public function fetchLeague($leagueID) {
		$dbleague = new DBLeague();
		$league = $dbleague->getLeague($leagueID);
		
		$dbteam = new DBTeam();
		$teams = new ArrayObject();
		
		$HT = $_SESSION['HT'];
	
		if ($HT instanceof CHPPConnection) {
			$htLeague = $HT->getLeague($leagueID);
			$league->setName($htLeague->getLeagueLevelName());
			$league->setUpdate(time());
			
			for ($i=1; $i<=8; $i++) {
				$htLeagueTeam = $htLeague->getTeam($i);
								
				$team = $dbteam->getTeamByID($htLeagueTeam->getTeamId());				
				$htTeam = $HT->getTeam($htLeagueTeam->getTeamId());
					
				if ($htTeam->isBot() || $htTeam->getUserId() == 0) {
					$dbteam->deleteTeamByID($htTeam->getTeamId());
					$dballiancemember = new DBAllianceMember();
					$dballiancemember->deleteAllianceMembershipByTeamID($htTeam->getTeamId());
					$dbflag = new DBFlag();
					$dbflag->deleteFlagsByTeamID($htTeam->getTeamId());
				}
				else {
					if (!isset($team)) {
						$team = new Team($htTeam->getTeamId(), $htTeam->getTeamName());
					}
					else if ($htTeam->getUserId() != $team->getUserID()) {
						$dbteam->deleteTeamByID($htTeam->getTeamId());
						$dballiancemember = new DBAllianceMember();
						$dballiancemember->deleteAllianceMembershipByTeamID($htTeam->getTeamId());
						$dbflag = new DBFlag();
						$dbflag->deleteFlagsByTeamID($htTeam->getTeamId());
						$team = new Team($htTeam->getTeamId(), $htTeam->getTeamName());
					}
					$team->setUserID($htTeam->getUserId());
					$team->setUserName($htTeam->getLoginName());
					$team->setActivationDate($htTeam->getActivationDate());
					
					$logicTeam = new LogicTeam();
					$team->setNTCoach($logicTeam->isNTCoach($htTeam));
					$team->setU20Coach($logicTeam->isU20Coach($htTeam));
					
					$team->setLeague($league);
					
					$teams->append($team);
				}
			}
			$dbteam->saveTeams($teams);
			$dbleague->saveLeague($league);
			
			$HT->clearTeams();
			$HT->clearLeague($leagueID);
			
			return $league;
		}
		else throw new Exception("(0)");
	}
	
}

?>